<template>
    <div style="padding:30px;">
      <el-alert
          title="坐席管理"
          type="info"
          :closable="false"
          show-icon
          description="user查询,admin可编辑"
          effect="dark"/>
      <div class="app-container">
      <el-input v-model="listQuery.train_number" placeholder="输入车次" style="width: 200px;" class="filter-item"  />
      <el-date-picker
      v-model="listQuery.arrive_day"
      value-format="yyyy-MM-dd"
      align="right"
      type="date"
      placeholder="选择日期"
      :picker-options="pickerOptions">
    </el-date-picker>
      <el-button  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <!-- 添加按钮 -->
        <el-button v-has="'add'" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          添加
        </el-button>
      <el-table
        v-loading="listLoading"
        :data="list2"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column align="center" label="编号" >
          <template slot-scope="scope">
            {{ scope.row.train_no}}
          </template>
        </el-table-column>

        <el-table-column align="center" prop="created_at" label="发车时间" width="200">
          <template slot-scope="scope">
            <i class="el-icon-time" />
            <span>{{ scope.row.arrive_day }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车厢号"  align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.carriage_no }}</span>
          </template>
        </el-table-column>
        <el-table-column label="座位类型"  align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.seat_type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="座位总数"  align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.seat_count }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="handleHas()" label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleUpdate(row,$index)" >
              编辑
            </el-button>
            <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total"  :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getplist" />
      <el-dialog :visible.sync="dialogFormVisible">
        <el-form :model="temp" ref="dataForm" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
          <el-form-item label="编号" prop="train_no">
          <el-input v-model="temp.train_no" :disabled="dialogStatus=='update'" />
        </el-form-item>
        <el-form-item label="发车日期" prop="arrive_day">
          <el-date-picker
          :disabled="dialogStatus=='update'"
          v-model="temp.arrive_day"
          type="date"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          placeholder="选择日期">
        </el-date-picker>
        </el-form-item>
        <el-form-item label="车厢号" prop="carriage_no">
          <el-input v-model="temp.carriage_no" />
        </el-form-item>
        <el-form-item label="座位类型" prop="seat_type">
          <el-input v-model="temp.seat_type" :disabled="true" />
        </el-form-item>
        <el-form-item label="座位总数" prop="seat_count">
          <el-input v-model="temp.seat_count"  :disabled="true"/>
        </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
        <!-- 取消 -->
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <!-- 确定 -->
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
      </el-dialog>
      </div>
    </div>
  </template>
  
  <script>
  import { queryAllCarriage,queryCarriage,deleteCarriage,addCarriage,editCarriage} from '@/api/train'
  import { mapGetters } from 'vuex'
  import Pagination from '@/components/Pagination'
  import hasDirective from "@/directives/has";
  
  export default {
    name:"Carriage",
    components: { Pagination },
    directives: {
      has: hasDirective,
    },
    data() {
      return {
        rowid:0,
        listLoading:false,
        dialogStatus:'',//对话框的状态，是添加，还是编辑
        dialogFormVisible: false,//对话框是否可见，初始不可见
        total:0,
        listQuery:{
          train_number:'',
          arrive_day:'',
          page:1,
          limit:5,
        },
        list:[],
        list2:[],
        temp:{
          train_no:'',
          carriage_no:'',
          seat_count:'',
          arrive_day:'',
          seat_type:'',
        },
        pickerOptions: {
            disabledDate(time) {
              return time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000;
            },
            shortcuts: [{
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date());
              }
            }]
          },
      }
    },
    created(){
      this.fetchData()
    },
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    watch:{
      'temp.carriage_no':{
        handler(newVal,oldVal){
          if(newVal=='1'||newVal=='2'){
            this.temp.seat_type='商务座'
            this.temp.seat_count=20
          }
          else if(newVal=='3'||newVal=='4'){
            this.temp.seat_type='一等座'
            this.temp.seat_count=30
          }
          else{
            this.temp.seat_type='二等座'
            this.temp.seat_count=50
          }
        },
      }
    },
    methods: {
      handleHas(){
        if(JSON.parse(localStorage.getItem('permissions')).includes('editAndDelete')){
          return 1
        }
        else{
          return 0
        }
      },
      fetchData(){
        this.listLoading = true
        queryAllCarriage().then(response =>{
          this.list=response.data.data
          this.total = this.list.length
          this.list2=this.list.slice(0,this.listQuery.limit);
          this.listLoading = false
        })
      },
      getplist(){
    this.listLoading=true; 
    this.list2=this.list.slice((this.listQuery.page-1)*this.listQuery.limit,(this.listQuery.page)*this.listQuery.limit)
    this.listLoading=false;
      },
      handleFilter(){
        this.listLoading=true
        if(this.listQuery.arrive_day=='' || this.listQuery.train_number==''){
          this.fetchData()
        }
        else{
          queryCarriage({arrive_day:this.listQuery.arrive_day,train_number:this.listQuery.train_number}).then(response =>{
            this.list=response.data.data
            console.log(this.list)
            this.total = this.list.length
            this.list2=this.list.slice(0,this.listQuery.limit);
            this.listLoading = false
          })
        }
      },
      handleDelete(row, index) {
    this.$confirm('此操作将删除该车次的信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$notify({
      title: '成功',
      message: '删除成功',
      type: 'success',
      duration: 2000
    })
    // 删除数组中指定元素
    this.list2.splice(index, 1)
    this.total=this.total-1
    console.log(row, "@@@")
    deleteCarriage({train_no:row.train_no,carriage_no:row.carriage_no,arrive_day:row.arrive_day})
      }).catch(() => {
        this.$notify.info({
      title: '取消',
      message: '取消删除',
      duration: 2000
    })      
      });
      },
      createData() {
        // 新增接口
        addCarriage(this.temp).then((response) => {
          // 追加新增数据
          this.list2.unshift(this.temp)
          this.total=this.total+1
          // 模态框不可见
          this.dialogFormVisible = false
          // 提示信息
          this.$notify({
            title: 'Success',
            message: 'Created Successfully',
            type: 'success',
            // 持续时间
            duration: 2000
          })
        })

      },
      resetTemp() {
      this.temp = {
        train_no:'',
          carriage_no:'',
          seat_count:'',
          arrive_day:'',
          seat_type:'',
      }
      },
      handleCreate() {
  // 重设默认值
  this.resetTemp()
  this.dialogStatus = 'create'
  // 设置模态框可见
  this.dialogFormVisible = true
  // $nextTick：在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法，获取更新后的 DOM。
  // 使用nextTick可立即使用更完的DOM
  this.$nextTick(() => {
    // 移除表单校验结果
    this.$refs['dataForm'].clearValidate()
    // 移除校验结果并重置字段值 (未测试)
    // this.$refs['dataForm'].resetFields()
  })
      },
      handleUpdate(row,index) {
    this.rowid=index
    this.temp = Object.assign({}, row) // copy obj
    this.dialogStatus = 'update'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      this.$refs['dataForm'].clearValidate()
    })
  },
  updateData() {
    this.$refs['dataForm'].validate(() => {
        const tempData = Object.assign({}, this.temp)
        editCarriage(tempData).then(() => {
          const index = this.rowid
          this.list2.splice(index, 1, this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        })
    })
  },
    }
  }
  </script>
  